package com.uh.rds.testing.validator.types;

import com.uh.rds.testing.validator.DataValidatorBase;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class SetDataValidator extends DataValidatorBase {

    @Override
    public String getType() {
        return "Set";
    }

    @Override
    public void process() {
        if(processJedis.isConnected() == false)  processJedis.connect();

        processBeginLog();
        for(Map.Entry<String, List<String[]>> entry : data.entrySet()) {
            String key = entry.getKey();
            boolean succeed = true;
            Collection<String[]> valuesList = entry.getValue();
            for (String[] values : valuesList) {
                String value = values[0];
                if(processJedis.sadd(key, value) != 1) {
                    logger.error("{} key[{}] value[{}] insert failed!", getName(), key, value);
                    succeed = false;
                }
            }

            processingLog(succeed);
        }

        processEndLog();
    }

    @Override
    public long expire(int expireSeconds) {
        return super.expire(processJedis, data.keySet(), expireSeconds);
    }

    public boolean validateExpired() {
        return super.validateExpired(validateJedis, data.keySet());
    }


    @Override
    public boolean validate() {
        if(validateJedis.isConnected() == false)  validateJedis.connect();

        validateBeginLog();

        Collection<String> keys = arguments.isValidateReversed() ? reversedKeys : data.keySet();
        for(String key : keys) {
            boolean keyMatched = true;
            List<String[]> valuesList = data.get(key);

            int subSizeExpected = valuesList.size();
            long subSizeActual = validateJedis.scard(key);
            if(subSizeActual != subSizeExpected) {
                keyMatched = false;
                logger.error("{} key[{}] validate failed! Expected size:{} actual size:{}", getName(), key, subSizeExpected, subSizeActual);
            }


            for (String[] values : valuesList) {
                String expectedValue = values[0];
                boolean valueMatched = validateJedis.sismember(key, expectedValue);
                if (valueMatched == false) {
                    keyMatched = false;
                    logger.error("{} key[{}] validate failed! Expected sub value:{} not found!", getName(), key, expectedValue);
                    break;
                }
            }

            validatingLog(keyMatched);
        }

        return validateEndLog();
    }

    @Override
    public long clear() {
        return clear(processJedis, validateJedis, data.keySet());
    }

}
